package com.zhangx.datastructure.stacklist;

/**
 * @ClassName LinkQueue
 * @Description 链式队列
 * 头尾都指向头结点就是空
 * P117
 * @Author zhangx
 * @Date 2021/1/4 8:34
 **/
public class LinkQueue {

    QNode front;
    QNode rear;

    @Override
    public String toString() {
        return "LinkQueue{" +
                "front=" + front +
                ", rear=" + rear +
                '}';
    }

    static class QNode{
        int data;
        QNode next;

        @Override
        public String toString() {
            return "QNode{" +
                    "data=" + data +
                    ", next=" + next +
                    '}';
        }
    }

    public LinkQueue(){
        QNode top = new QNode();
        top.data = -1;
        front = top;
        rear = top;
    }

    /**
     * 入队列
     * @param num
     */
    public void enQueue(int num){
        QNode node = new QNode();
        node.data = num;
        node.next = null;
//      附加在尾节点后面
        rear.next = node;
//      成为新的尾节点
        rear = node;
    }

    /**
     * 出栈
     * @return
     */
    public QNode deQueue(){
        if (front.next == null){
            System.out.println("空队列");
            return null;
        }

        QNode node = front.next;
//      top节点不出栈
        front.next = node.next;
//        就剩下头结点了，也要改一下队尾节点的指向
        if (front.next == null){
            rear = front;
        }
        return node;
    }

    public static void main(String[] args) {
        LinkQueue linkQueue = new LinkQueue();
        System.out.println(linkQueue);
        linkQueue.enQueue(1);
        System.out.println(linkQueue);
        System.out.println(linkQueue.deQueue());
        System.out.println(linkQueue);

    }
}
